package cn.kgc.viny.smbms.web;

import cn.kgc.viny.smbms.entity.Address;
import cn.kgc.viny.smbms.entity.Role;
import cn.kgc.viny.smbms.entity.User;
import cn.kgc.viny.smbms.service.AddressService;
import cn.kgc.viny.smbms.service.Constant;
import cn.kgc.viny.smbms.service.RoleService;
import cn.kgc.viny.smbms.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private AddressService addressService;

    @RequestMapping("/showAddressByUserId")
    @ResponseBody
    public List<Address> showAddressByUserId(Long userId) {
        return this.addressService.findAddressByUserId(userId);
    }

    @RequestMapping("/showUsersByRoleId")
    @ResponseBody
    public Object showUsersByRoleId(Long roleId) {
        List<User> userList = this.userService.findUsersByRoleId(roleId);
        return userList;
    }

    @RequestMapping("/showList")
    public String showList(Model model, User condition, Integer pageNum) {
        if (pageNum == null)
            pageNum = 1;
        Integer pageSize = 3;
        PageInfo<User> pageInfo = this.userService.find(condition, pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        fetchRoleList(model);
        //转发
        return "user/list";//WEB-INF/smbms/user/list.jsp
    }

    private void fetchRoleList(Model model) {
        List<Role> roleList = this.roleService.findAll();
        model.addAttribute("roleList", roleList);
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model, User user) {
        this.fetchRoleList(model);
        return "user/add";//WEB-INF/smbms/user/add.jsp
    }
//    @RequestMapping("/toAdd")
//    public String toAdd(Model model) {
//        this.fetchRoleList(model);
//        model.addAttribute("user",new User());
//        return "user/add";//WEB-INF/smbms/user/add.jsp
//    }

    //    @RequestMapping("/add")
//    public String add(@Valid User user, BindingResult bindingResult, Model model, HttpSession session, MultipartFile pic) throws Exception{
//        if(bindingResult.hasErrors()){
//            this.fetchRoleList(model);
//            return "user/add";//WEB-INF/smbms/user/add.jsp
//        }
//        System.out.println("pic.isEmpty() = " + pic.isEmpty());
//        if(pic.isEmpty()==false){
//            //文件的扩展名
//            //.JPG,.Jpg
//            String extendsName=pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
//            List<String> allowedExtendsName= Arrays.asList(".jpg",".jpeg",".png",".gif");
//            if(allowedExtendsName.contains(extendsName.toLowerCase())==false){
//                throw new Exception("文件扩展名不被允许，允许：\".jpg\",\".jpeg\",\".png\",\".gif\"");
//            }
//            String serverDirectory=session.getServletContext().getRealPath(File.separator+"userPic");
//            System.out.println("serverDirectory = " + serverDirectory);
//            String fileName=System.currentTimeMillis()+"-"+new Random().nextInt(9999);
//            fileName=fileName+extendsName;
//            System.out.println("fileName = " + fileName);
//            File targetFile=new File(serverDirectory,fileName);
//            pic.transferTo(targetFile);
//            user.setUserPicName(fileName);
//        }
//        user.setCreatedBy((User)session.getAttribute(Constant.USER));
//        user.setCreationDate(new java.util.Date());
//        this.userService.add(user);
//        return "redirect:showList";
//    }
    @RequestMapping("/add")
    public String add(@Valid User user, BindingResult bindingResult, Model model,
                      HttpSession session, @RequestParam(value = "pic", required = false) MultipartFile[] picArray) throws Exception {
        if (bindingResult.hasErrors()) {
            this.fetchRoleList(model);
            return "user/add";//WEB-INF/smbms/user/add.jsp
        }
        System.out.println("picArray = " + picArray);
        String extendsName;
        List<String> allowedExtendsName = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        //服务器存放图片的地址
        String serverDirectory = session.getServletContext().getRealPath(File.separator + "userPic");
        //文件名
        String fileName;
        //File targetFile
        File targetFile;
        //StringBuilder存文件名
        StringBuilder builder = new StringBuilder();
        for (MultipartFile pic : picArray) {
            System.out.println("pic.isEmpty() = " + pic.isEmpty());
            if (pic.isEmpty() == false) {
                //文件的扩展名,.JPG,.Jpg
                extendsName = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
                if (allowedExtendsName.contains(extendsName.toLowerCase()) == false) {
                    throw new Exception("文件扩展名不被允许，允许：\".jpg\",\".jpeg\",\".png\",\".gif\"");
                }
                fileName = System.currentTimeMillis() + "-" + new Random().nextInt(9999);
                fileName = fileName + extendsName;
                targetFile = new File(serverDirectory, fileName);
                pic.transferTo(targetFile);
                builder.append(fileName+",");
            }
        }
        //54343543543-5433.jpg,43432432424-5435.jpg,
        if(builder.length()!=0)
            user.setUserPicName(builder.substring(0,builder.length()-1));
        user.setCreatedBy((User) session.getAttribute(Constant.USER));
        user.setCreationDate(new java.util.Date());
        this.userService.add(user);
        return "redirect:showList";
    }

    @ExceptionHandler({Exception.class})
    public String handlerException(Exception exception, HttpServletRequest request) {
        request.setAttribute("exception", exception.getMessage());
        return "error";//WEB-INF/smbms/error.jsp
    }

    @RequestMapping("/showUser")
    @ResponseBody
    public Object showUser(Long userId) {
        User user = this.userService.findById(userId);
        return user;
    }
    @RequestMapping(value = "/showUserById/{userId}/{userCode}",method = RequestMethod.GET)
    public String showUserById(@PathVariable Long userId,@PathVariable String userCode, Model model){
        User user=this.userService.findById(userId);
        model.addAttribute("user",user);
        System.out.println("userCode="+userCode);
        return "user/detail";
    }
//    @RequestMapping(value = "/showUser",produces = "application/json;charset=utf-8")
//    @ResponseBody
//    public String showUser(Long userId) {
//        PrintWriter out = null;
//        User user = this.userService.findById(userId);
//        String jsonString = JSON.toJSONString(user);
//        return jsonString;
//    }

    //    @RequestMapping("/showUser")
//    public void showUser(Long userId,HttpServletResponse response){
//        PrintWriter out = null;
//        try {
//            User user=this.userService.findById(userId);
//            String jsonString= JSON.toJSONString(user);
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json;charset=utf-8");
//            out = response.getWriter();
//            out.print(jsonString);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } finally {
//            if(out!=null){
//                out.flush();
//                out.close();
//            }
//        }
//    }
//    @RequestMapping("/showUser")
//    public void showUser(Long userId,HttpServletResponse response){
//        PrintWriter out = null;
//        try {
//            User user=this.userService.findById(userId);
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json;charset=utf-8");
//            out = response.getWriter();
//            out.print("{\"userId\":"+user.getUserId()+",\"userName\":\""+user.getUserName()+"\",\"birthday\":\""+user.getBirthday()+"\"}");
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } finally {
//            if(out!=null){
//                out.flush();
//                out.close();
//            }
//        }
//    }
    @RequestMapping("/checkUserCode")
    @ResponseBody
    public String checkUserCode(String userCode, HttpServletResponse response) {
        Integer count = this.userService.findUserCount(userCode);
        return count.toString();
    }

    @RequestMapping("/checkUserCode01")
//    @ResponseBody
    public void checkUserCode01(String userCode, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            Integer count = this.userService.findUserCount(userCode);
//        return count.toString();
            out = response.getWriter();
            out.print(count);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}
